import { Point } from "..";
import _ from "lodash";

/**
 * 将鼠标事件坐标转换为在canvas中的坐标
 * @param ctx
 * @param x : mouse
 * @param y
 * @returns
 */
export function clientPosCvt(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number
): Point;

/**
 * 将鼠标事件坐标转换为在canvas中的坐标
 * @param ctx
 * @param mouseEvent
 * @returns
 */
export function clientPosCvt(
  ctx: CanvasRenderingContext2D,
  mouseEvent: MouseEvent
): Point;

export function clientPosCvt(
  ctx: CanvasRenderingContext2D,
  arg1: number | MouseEvent,
  arg2?: number
) {
  let [x, y] = [0, 0];
  if (_.isNil(arg2)) {
    const mouseEvent: MouseEvent = arg1 as MouseEvent;
    x = mouseEvent.clientX;
    y = mouseEvent.clientY;
  } else {
    x = arg1 as number;
    y = arg2!;
  }
  const canvas = ctx.canvas;
  const bbox = canvas.getBoundingClientRect();
  const cs = getComputedStyle(canvas);
  // 在 canvas 中的坐标需要减去 padding-left/right 以及 border-left/right
  const oLeft = parseFloat(cs.borderLeft) + parseFloat(cs.paddingLeft);
  const oTop = parseFloat(cs.borderTop) + parseFloat(cs.paddingTop);
  const oRight = parseFloat(cs.borderRight) + parseFloat(cs.paddingRight);
  const oBottom = parseFloat(cs.borderBottom) + parseFloat(cs.paddingBottom);
  const px = x - bbox.x - oLeft;
  const py = y - bbox.y - oTop;
  const pw = bbox.width - oLeft - oRight;
  const ph = bbox.height - oTop - oBottom;
  // 可能存在 canvas 通过 style 修改 width、height 大小，导致 canvas 内容缩放，因此需要调整坐标
  // px / pw = rx / width
  return { x: (px * canvas.width) / pw, y: (py * canvas.height) / ph };
}
